package org.testframe;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 集合点
 * @author 丁常磊
 * @date 2023/11/17 16:36
 */

public class Gather {

    private final int target;

    private volatile int currentCount = 0;

    private volatile Object checkKey = new Object();

    private final Map<Action,Object> checkedMap = new HashMap<>();

    public Gather(int target) {
        this.target = target;
    }

    public synchronized boolean check(Action action) {
        Object o = checkedMap.get(action);
        if (o == null) {
            currentCount++;
            if (currentCount >= target) {
                //生成新的key
                checkKey = new Object();
                //重置数量
                currentCount = 0;
                return true;
            }else{
                checkedMap.put(action, checkKey);
            }
            return false;
        }else{
            if (o != checkKey) {
                checkedMap.remove(action);
                return true;
            }
            return false;
        }
    }

}
